package com.vipbbo.security.distributed.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.vipbbo.security.distributed.gateway.common.EncryptUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;

import java.util.*;

/**
 * @author bbo(zbw)
 * Description 转发明文token给微服务
 * @Date 2021/5/9
 */
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;// 数值越小越优先
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 从安全的上下文当中拿到用户身份对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof OAuth2Authentication)) {// 无token访问网关内资源的情况 目前仅有uaa服务直暴露
            return null;
        }
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)authentication;
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        // 获取当前用户的身份信息
        String principal = userAuthentication.getName();
        // 获取当前用户权限信息
        List<String> authorities = new ArrayList<>();
        // 从userAuthentication取出权限 放在authorities
        userAuthentication.getAuthorities().stream().forEach(c->authorities.add(((GrantedAuthority)c).getAuthority()));
        //
        OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();
        // 参数列表
        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
        Map<String,Object> jsonToken = new HashMap<>(requestParameters);

        if (userAuthentication!=null) {
            jsonToken.put("principal",principal);
            jsonToken.put("authorities",authorities);
        }
        // 把身份信息和权限信息放在json中  加入http的header中         // 转发给微服务
        currentContext.addZuulRequestHeader("json-token", EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(jsonToken)));

        return null;
    }
}
